package com.dpwgc.demo.service;

import com.dpwgc.demo.mapper.AdminMapper;
import com.dpwgc.demo.mapper.GroupMapper;
import com.dpwgc.demo.mapper.MessageMapper;
import com.dpwgc.demo.mapper.UserGroupMapper;
import com.dpwgc.demo.model.*;
import com.dpwgc.demo.utils.DateUtil;
import com.dpwgc.demo.utils.ResultUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import java.util.List;

/**
 * 管理员相关操作
 */
@Service
public class AdminService {

    @Autowired
    AdminMapper adminMapper;

    @Autowired
    UserGroupMapper userGroupMapper;

    @Autowired
    MessageMapper messageMapper;

    @Autowired
    GroupMapper groupMapper;

    @Autowired
    DateUtil dateUtil;

    /**
     * 新建管理员
     * @param userId 用户id
     * @param groupId 群组id
     * @param lv
     * @return
     */
    public ResultUtil<Object> insertAdminService(int userId,int groupId,int lv){

        ResultUtil<Object> resultUtil = new ResultUtil<>();

        Admin admin = new Admin();
        admin.setUserId(userId);
        admin.setGroupId(groupId);
        admin.setLv(lv);
        admin.setCreateTime(dateUtil.getDateTime());
        admin.setUpdateTime(dateUtil.getDateTime());
        admin.setStatus(1);

        resultUtil.setCode(200);
        resultUtil.setMsg("操作成功");
        resultUtil.setData(adminMapper.insert(admin));

        return resultUtil;
    }

    /**
     * 根据群组id获取申请加入群组的用户列表
     * @param groupId 群组id
     * @return
     */
    public ResultUtil<Object> queryUserApplyByGroupIdService(int groupId){

        ResultUtil<Object> resultUtil = new ResultUtil<>();

        List<User> users = groupMapper.queryUserApplyByGroupId(groupId);

        resultUtil.setCode(200);
        resultUtil.setMsg("操作成功");
        resultUtil.setData(users);
        return resultUtil;
    }

    /**
     * 批准用户加入群组
     * @param userId 用户id
     * @param groupId 群组id
     * @return
     */
    public ResultUtil<Object> userJoinGroupService(int userId,int groupId){

        ResultUtil<Object> resultUtil = new ResultUtil<>();

        UserGroup userGroup = new UserGroup();
        userGroup.setUserId(userId);
        userGroup.setGroupId(groupId);
        userGroup.setLookNum(0);
        userGroup.setCreateTime(dateUtil.getDateTime());
        userGroup.setUpdateTime(dateUtil.getDateTime());

        //检查用户是否加入该群聊
        UserGroup ug = userGroupMapper.checkUserGroup(userId,groupId);

        if(ug == null || ug.getStatus() != 1){
            //用户加入群聊
            int i = userGroupMapper.userJoinGroup(userGroup);

            //插入用户加入群聊的消息
            Message message = new Message();
            message.setUserId(userId);
            message.setGroupId(groupId);
            message.setMessageData("用户"+userId+"已加入群");
            message.setCreateTime(dateUtil.getDateTime());
            message.setUpdateTime(dateUtil.getDateTime());
            message.setStatus(1);
            messageMapper.insert(message);

            //更新群组信息
            Group group = groupMapper.queryGroupById(groupId);
            group.setGroupText("用户"+userId+"已加入群");
            group.setUpdateTime(dateUtil.getDateTime());
            groupMapper.updateGroupById(group);

            resultUtil.setCode(200);
            resultUtil.setMsg("操作成功");
            resultUtil.setData(userGroup);
            return resultUtil;
        }
        else {
            resultUtil.setCode(100);
            resultUtil.setMsg("用户已加入该群");
            resultUtil.setData("");
            return resultUtil;
        }
    }

    /**
     * 判断用户是否是该群管理员 & 检查管理员等级
     * @param userId 用户id
     * @param groupId 群组id
     * @return
     */
    public ResultUtil<Object> checkAdminLvService(int userId,int groupId){

        ResultUtil<Object> resultUtil = new ResultUtil<>();

        Admin admin = adminMapper.checkAdminLv(userId, groupId);
        if(admin == null){
            resultUtil.setCode(100);
            resultUtil.setMsg("用户无管理员权限");
            resultUtil.setData(0);
            return resultUtil;
        }
        else {
            resultUtil.setCode(200);
            resultUtil.setMsg("用户有管理员权限");
            resultUtil.setData(admin.getLv());//返回管理员等级
            return resultUtil;
        }
    }

    /**
     * 群主撤销管理员权限
     * @param userId 用户id
     * @param groupId 群组id
     * @return
     */
    public ResultUtil<Object> deleteAdminService(int userId,int groupId){

        ResultUtil<Object> resultUtil = new ResultUtil<>();

        int i = adminMapper.deleteAdmin(userId, groupId);
        resultUtil.setCode(200);
        resultUtil.setMsg("操作成功");
        resultUtil.setData("");
        return resultUtil;
    }

    /**
     * 群主权限转让
     * @param userId 新群主的用户id
     * @param groupId 群组id
     * @param optUserId 当前群主的用户id
     * @return
     */
    public ResultUtil<Object> leaderTransferService(int userId,int groupId,int optUserId){

        ResultUtil<Object> resultUtil = new ResultUtil<>();

        //检查执行该操作的用户是否有群主权限（optUserId：执行该操作的用户id，即群主的用户id）
        Admin admin = adminMapper.checkAdminLv(optUserId, groupId);
        if(admin.getLv() != 1){
            resultUtil.setCode(100);
            resultUtil.setMsg("用户无群主权限");
            resultUtil.setData(0);
            return resultUtil;
        }

        //开启事务
        try{

            int i1 = adminMapper.updateAdminLv(optUserId, groupId,2);//旧群主等级下降
            int i2 = adminMapper.updateAdminLv(userId, groupId,1);//新群主等级上升

            resultUtil.setCode(200);
            resultUtil.setMsg("操作成功");
            resultUtil.setData("");
            return resultUtil;

        } catch (Exception e) {
            e.printStackTrace();
            //设置手动回滚
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();

            resultUtil.setCode(100);
            resultUtil.setMsg("操作失败");
            resultUtil.setData("");
            return resultUtil;
        }
    }
}
